<template>
  <view>
    <view v-if="(CashData.isShowDistributionButton||isShowBtn)">
      <view class="m-endorsementBox">
        <view class="m-endorsementBox-bg">
        </view>
        <view class="m-userInfo">
          <view class="m-photo">
            <image lazy-load :src="(userInfo.user_avatar)"></image>
          </view>
          <view class="m-text">
            <label>{{ sprintf(__('我是%s'), userInfo.user_nickname) }}</label>
            <text>{{ sprintf(__('我为%s代言'), plantformInfo.site_name || "-") }}</text>
          </view>
        </view>
      </view>
      <view class="u-toptip" v-if="(ProductInfo!=null)">
        <view class="u-loadmore u-loadmore-line">
          <text class="u-loadmore-tips">{{ __('为您推荐') }}</text>
        </view>
      </view>
      <view class="m-product-list" v-if="(ProductInfo!=null)">
        <navigator open-type="redirect" :url="(ProductUrl) + '?pid=' + (ProductInfo.pid) + '&uid=' + (userInfo.user_id)"
                   class="m-product-item">
          <view class="m-product-img">
            <image lazy-load :src="(ProductInfo.ppic)" mode="aspectFill"/>
          </view>
          <view class="m-product-info">
            <view class="m-product-name">
              <label>{{ ProductInfo.pname }}</label>
            </view>
            <view class="m-product-price">
              <label>{{ __('￥') }}</label>{{ ProductInfo.pprice }}
              <button class="u-btn u-btn-default">{{ buyname }}</button>
            </view>
          </view>
        </navigator>
      </view>

      <view @click='previewImg'>
        <image lazy-load v-if="(ProductInfo==null)" :src="(invite_qrcode)" class="QRCodeBOx" mode="widthFix"></image>
      </view>

      <view class="m-text-box" v-if="(RuleEnabled&&flag==false)">
        <view @click="showTip">
          <label class="iconfont icon-14052218"></label>{{ __('推广规则') }}
        </view>
        <view>
          <view>
            {{
              sprintf(__('当你的粉丝在店铺内支付订单后，订单中的所有商品，都有相应的收益比例：一级粉丝 %s%% ，二级粉丝 %s%% 。将支付订单金额和收益比例相乘后，累计计算出你此单的总收益。* 注： - 不计算收益的内容：运费、优惠券、关税，以及收益比例为0的商品；'), plantformInfo.plantform_fx_cps_rate_1, plantformInfo.plantform_fx_cps_rate_2)
            }}
            {{ __(' - 如果发生了退货退款，需要按照实际退货数量对收益进行相应的扣除；- 按照国家法律规定，当你的月累计收入达到相关税金起征点后，商家会为你代缴税款，你的收益将是税后收入；') }}
          </view>
        </view>
      </view>
      <view class="m-text-box" v-else>
        <view @click="showTip">
          <label class="iconfont icon-14052218"></label>{{ __('推广规则') }}
        </view>
        <view>
          <view><!--{{ __('成功邀请一位好友，可获积分奖励：') }} <label
              style="color:red;padding-left:10rpx;">{{ plantformInfo.plantform_fx_gift_point }}</label>{{ __('枚') }}, -->
            {{ __('当好友产生消费时，获得相应佣金奖励') }}
          </view>
        </view>
      </view>

      <view class="m-text-box1" v-if="(RuleEnabled&&flag)">
        <rich-text :nodes="htmlString"></rich-text>
      </view>


      <!-- #ifdef H5 -->
      <button v-if="(ProductInfo==null && isShowBtn==false && CashData.isShowDistributionButton)"
              class="u-btn u-btn-default"
              @click="onShareBox">{{ __('分享赚钱') }}
      </button>
      <!-- #endif -->
      <!-- #ifdef MP-WEIXIN -->
      <navigator v-if="(ProductInfo==null && isShowBtn && CashData.isShowDistributionButton)"
                 class="u-btn u-btn-default"
                 @click="share">{{ __('我也要代言') }}
      </navigator>
      <navigator class="u-btn u-btn-default" @click="share" v-if="(ProductInfo!=null &&isShowBtn)">{{ __('我也要推广') }}
      </navigator>
      <button v-if="(ProductInfo==null && isShowBtn==false && CashData.isShowDistributionButton)"
              class="u-btn u-btn-default"
              @click="onShareBox">{{ __('分享赚钱') }}
      </button>
      <!-- #endif -->
      <!-- #ifdef APP-PLUS -->
      <navigator v-if="(ProductInfo==null && isShowBtn && CashData.isShowDistributionButton)"
                 class="u-btn u-btn-default"
                 @click="share">{{ __('我也要代言') }}
      </navigator>
      <navigator class="u-btn u-btn-default" @click="share" v-if="(ProductInfo!=null &&isShowBtn)">{{ __('我也要推广') }}
      </navigator>
      <button v-if="(ProductInfo==null && isShowBtn==false && CashData.isShowDistributionButton)"
              class="u-btn u-btn-default"
              @click="onShareBox">{{ __('分享赚钱') }}
      </button>
      <!-- #endif -->

      <view class="u-tap-btn">
        <navigator url="/pages/index/index" open-type="switchTab" class="u-go-home">
          <view class="iconfont icon-shouyeshouye"></view>
        </navigator>
      </view>

      <view class="m-msk" v-if="(isShowMag)" @click="closeMsk">
        <image lazy-load mode="widthFix" :src="(plantformInfo.site_mobile_logo) + 'share_tips.png'"></image>
      </view>
    </view>
    <navigator url="/pages/index/index" open-type="switchTab" class="m-nullpage"
               v-if="(CashData.isShowDistributionButton==false&&isShowBtn==false)">
      <view class="m-nullpage-middle">
        <view class="m-null-tip">
          <text>{{ __('对不起，您现在还没有分销权限') }}</text>
          <text>{{ __('多多购物有助于获取权限哦。') }}</text>
        </view>
      </view>
    </navigator>

    <share-box-app :shareDataDefault="shareData" ref="shareBoxApp"></share-box-app>
    <share-box-mp :shareDataDefault="shareData" @cancelShare="cancelShare" @showCodeImg="showCodeImg"
                  @shareQRCode="shareQRCode"
                  @saveImg="saveImg" ref="shareBoxMp"></share-box-mp>

    <l-painter useCORS @success="createPoster($event)" isCanvasToTempFilePath ref="painter" path-type="url" custom-style="position: fixed; left: 200%"></l-painter>
  </view>
</template>

<script>
import shareBoxMp from '../../components/share-box-mp.vue'
import shareBoxApp from '../../components/share-box-app.vue'

import {mapMutations, mapState} from 'vuex'

export default {
  data() {
    return {
      options: {},
      invite_qrcode: '',
      isShowBtn: false,
      ProductInfo: null,
      isShowMag: false,
      ProductUrl: "",
      buyname: "",
      PromotionRule: "",
      htmlString: "",
      RuleEnabled: true,
      flag: true,
      CashData: {},
      shareData: {},

      PageQRCodeInfo: {
        Path: "",
        IsShare: false,
        IsShareBox: false,
        IsJT: false
      },

      //BEGIN 生成海报参数
      productPoster: '',
      show: false,
      poster: {
        css: {
          width: "750rpx",
          height: '1334rpx',
          background: '#fff'
        },
        views: [{
          type: "image",
          src: "背景图片",
          css: {
            left: '0rpx',
            top: '0rpx',
            width: '750rpx',
            height: '1334rpx',
            position: "fixed"
          }
        },{
          type: "image",
          src: "用户头像",
          css: {
            left: '600rpx',
            top: '40rpx',
            width: '120rpx',
            height: '120rpx',
            position: "fixed",
            borderRadius:'20rpx'
          }
        },{
          type: 'text',
          text: '用户昵称',
          css: {
            position: "fixed",
            right: '40rpx',
            top: '180rpx',
            fontSize: '20rpx',
            color: '#fff'
          }
        },{
            type: "image",
            src: "二维码图片",
            css: {
              left: '210rpx',
              top: '590rpx',
              width: '330rpx',
              height: '330rpx',
              position: "fixed"
            }
          },{
            type: 'text',
            text: '长按保存或扫码查看',
            css: {
              position: "fixed",
              left: '285rpx',
              top: '940rpx',
              fontSize: '20rpx',
              color: '#fff'
            }
          }]
      },
      //END 商品海报信息
    };
  },

  components: {
    shareBoxMp,
    shareBoxApp
  },
  watch: {
    plantformInfo(newVal, oldVal) {
      console.info(oldVal)
      console.info(newVal)

	    this.plantformInfo = newVal;

		this.poster.views[0].src = newVal.plantform_poster_bg;
    },
    userInfo(newVal, oldVal) {
      this.userInfo = newVal;
    this.poster.views[1].src = newVal.user_avatar;
    this.poster.views[2].text = newVal.user_nickname;
    }
  },
  computed: mapState(['Config', 'StateCode', 'notice', 'plantformInfo', 'shopInfo', 'userInfo', 'hasLogin']),
  async onLoad(options) {
    let that = this
    uni.setNavigationBarTitle({
      title: this.__('我要代言')
    });

    this.setData({
      options: options
    })

    that.$.isNull(options.type) ? this.setData({
      ProductUrl: "/pagesub/product/detail",
      buyname: that.__('去购买')
    }) : this.setData({
      ProductUrl: "/pagesub/product/detail",
      buyname: that.__('去预约')
    });

    if (that.$.isNull(this.userInfo)) {
      this.forceuserInfo(function (user) {
        if (user) {
          that.setData({
            isShowBtn: that.$.isNull(options.uid) ? false : true
          });
          that.showButton();
          that.getPageInfo(that.$.isNull(options.uid) ? that.userInfo.user_id : options.uid)
        }
      });

    } else {
      this.setData({
        isShowBtn: that.$.isNull(options.uid) ? false : true
      });
      this.showButton();
      this.getPageInfo(that.$.isNull(options.uid) ? this.userInfo.user_id : options.uid);

      if (that.$.isNull(options.pid)) {
        that.$.setNavigationBarTitle({
          title: that.__('我要代言')
        });
      } else {
        that.$.setNavigationBarTitle({
          title: that.__('我要推广')
        });

        this.setData({
          ProductInfo: options
        })

        this.getPlantformInfo(function (site) {
          that.setData({
            flag: true,
            RuleEnabled: site.promotion
          });

          that.htmlString = site.promotion.replace(/\\/g, "").replace(/<img/g,
              "<img style=\"display:none;\"");
        });
      }
    }

     this.poster.views[0].src = this.plantformInfo.plantform_poster_bg;
     this.poster.views[1].src = this.userInfo.user_avatar;
     this.poster.views[2].text = this.userInfo.user_nickname;
  },

  onBackPress() {
    if (this.$refs.shareBoxApp.showBoxView) {
      this.$refs.shareBoxApp.cancel();
      return true;
    }
  },
  onUnload() {
    if (this.$refs.shareBoxApp.showBoxView) {
      this.$refs.shareBoxApp.cancel()
    }
  },
  onNavigationBarButtonTap(e) {
    var that = this;

    if (e.index === 0) {
      that.onShareBox();
      /*
      that.setData({
        shareBoxFlag: 1,
        shareContetnFlag: 1
      })
      */
    } else {
      uni.showToast({
        title: "你点了收藏按钮",
        icon: "none"
      })
    }
  },
  onShareAppMessage: function () {
    let that = this;
    this.setData({
      isShowMag: false
    });
    var e, t, n;
    return that.$.isNull(this.ProductInfo) ? (e = "/member/fans/endorsement?uid=" + this.userInfo.user_id, t = this.userInfo.user_nickname +
        that.__('偷偷的告诉你，粉丝也能赚钱哦~')) : (e = "/member/fans/endorsement?pid=" + this.ProductInfo.pid + "&pname=" + this.ProductInfo.pname +
        "&pprice=" + this.ProductInfo.pprice + "&ppic=" + this.ProductInfo.ppic + "&uid=" + this.userInfo.user_id + "&type=" +
        this.ProductInfo.type, t = that.__('我发现这个商品很好，非常适合你哦！')), {
      title: t,
      desc: t,
      path: e
    }
  },
  methods: {
    ...mapMutations(['login', 'logout', 'getPlantformInfo', 'forceuserInfo', 'getuserInfo']),

    //生成的海报图片
    createPoster(e){
      this.productPoster = e
      if(this.productPoster){
        uni.hideLoading();
        this.$refs.shareBoxMp.path = this.productPoster;
      }
    },

    showButton: function () {
      var that = this,
          paremt = {
            user_id: this.userInfo.user_id
          };
      that.setData({
        CashData: {
          isShowDistributionButton: true
        }
      });
    },
    share: function () {
      this.getPageInfo(this.userInfo.user_id);
      this.setData({
        isShowBtn: false
      })
    },
    getPageInfo: function (e) {
      var that = this,
          params = {
            user_id: e,
            path: "pages/index/index?uid=" + e,
            width: 430
          };

      let $href = that.$.sprintf('%s/h5/pages/index/index?uid=%d', that.Config.SiteUrl, e);
      params['path'] = $href;

      // #ifdef H5
      params['poster_type'] = 1
      that.poster.views[3].type = 'qrcode';
      that.poster.views[3].text = $href;
      // #endif
      // #ifdef MP-WEIXIN
      params['poster_type'] = 2
      that.poster.views[3].type = 'image';
      // #endif
      // #ifdef APP-PLUS
      params['poster_type'] = 1

      // #endif

      //生成二维码并返回地址。 - 需要修改调整为小程序地址
      that.$.request({
        url: this.Config.URL.fx.poster,
        data: params,
        success: function (data, status, msg, code) {
          if (200 == status) {
            let qrcode_url = data.qrcode;

            if (data.qrcode.indexOf("?") != -1) {
              qrcode_url = data.qrcode + '&rand=' + Math.random()
            } else {
              qrcode_url = data.qrcode + '?rand=' + Math.random()
            }

            that.setData({
              invite_qrcode: qrcode_url
            });
            that.poster.views[3].src = qrcode_url;
          } else {
            that.setData({
              flag: false,
              ispage: false
            })
          }
        }
      });
    },
    closeMsk: function () {
      this.setData({
        isShowMag: false
      })
    },
    onShareBox: function (e) {
      let that = this;

      let $href = that.$.sprintf('%s/h5/pages/index/index?uid=%d', that.Config.SiteUrl, this.userInfo.user_id);

      // 如允许点击超链接跳转，则应该打开一个新页面，并传入href，由新页面内嵌webview组件负责显示该链接内容
      // #ifdef APP-PLUS
      $href = that.$.sprintf('%s/h5/pages/index/index?uid=%d', that.Config.SiteUrl, this.userInfo.user_id);
      // #endif
      // #ifdef MP-WEIXIN
      $href = "/pages/index/index?uid=" + this.userInfo.user_id;
      // #endif


      var path, title, image;


      if (that.$.isNull(this.ProductInfo)) {
        path = "/member/fans/endorsement?uid=" + this.userInfo.user_id;
        title = this.userInfo.user_nickname + that.__('偷偷的告诉你，粉丝也能赚钱哦~');
        image = this.plantformInfo.site_mobile_logo;
      } else {
        path = "/member/fans/endorsement?pid=" + this.ProductInfo.pid + "&pname=" + this.ProductInfo.pname +
            "&pprice=" + this.ProductInfo.pprice + "&ppic=" + this.ProductInfo.ppic + "&uid=" + this.userInfo.user_id + "&type=" +
            this.ProductInfo.type;

        title = that.__('我发现这个商品很好，非常适合你哦！');
        image = this.ProductInfo.ppic;
      }

      this.setData({
        shareData: {
          shareTitle: title,
          shareText: title,
          href: $href,
          image: image,
          price: 0
        }
      });


      // 如允许点击超链接跳转，则应该打开一个新页面，并传入href，由新页面内嵌webview组件负责显示该链接内容
      // #ifdef APP-PLUS
      this.$refs.shareBoxApp.show();
      // #endif

      // #ifdef MP-WEIXIN
      this.$refs.shareBoxMp.show();
      // #endif

      // #ifdef H5
      this.$refs.shareBoxMp.show();
      // #endif

    },

    cancelShare: function (e) {

    },

    showCodeImg: function (e) {

    },

    shareQRCode: function (e) {
      if(this.productPoster == ''){
        uni.showLoading({
          title: '海报生成中..',
          mask:true
        });
        this.$refs.painter.render(this.poster);
      }
    },

    saveImg: function (e) {

    },

    previewImg: function () {
      let that = this;
      that.$.previewImage({
        current: that.invite_qrcode,
        urls: [that.invite_qrcode]
      })
    }
  }
}
</script>

<style lang="scss">
@import "../../styles/_variables";

page {
  background-color: #fff;
}

.u-loadmore {
  margin: 60rpx auto 0 auto;
}

.u-loadmore-tips {
  background-color: #fff !important;
}

.m-endorsementBox {
  width: 100%;
  overflow: hidden;
  height: 240rpx;
  position: relative;
  text-align: center;
}

.m-endorsementBox-bg {
  height: 940rpx;
  width: 940rpx;
  background-color: #1e1c1d;
  -webkit-border-radius: 940rpx / 320rpx;
  border-radius: 940rpx / 320rpx;
  margin: 0 auto;
  margin-top: -700rpx;
  margin-left: -100rpx;
  position: relative;
}

.m-userInfo-bg {
  bottom: 20rpx;
  width: 400rpx;
}

.m-userInfo {
  z-index: 2;
  position: relative;
  display: inline-block;
  position: relative;
  top: -180rpx;
}

.m-userInfo .m-photo {
  width: 124rpx;
  height: 124rpx;
  float: left;
}

.m-photo image {
  width: 100%;
  height: 100%;
  border-radius: 100%;
}

.m-text {
  float: left;
  text-align: left;
  line-height: 40rpx;
  margin-top: 22rpx;
  margin-left: 20rpx;
  width: 360rpx;
}

.m-text {
  font-size: 24rpx;
  color: #eebe8c;
}

.m-text label {
  font-size: 32rpx;
  font-weight: bold;
}

.m-text text {
  display: block;
}

.m-product-info::before {
  content: "";
  border: none;
}

.u-btn {
  margin-top: 80rpx;
}

.u-tip-text {
  display: block;
  font-size: 28rpx;
  text-align: center;
  color: $default-skin-bg
}

.m-product-price .u-btn {
  margin: 0;
  float: right;
  width: 160rpx;
  height: 60rpx;
  font-size: 24rpx;
  margin-right: 20rpx;
  margin-top: -30rpx;
}

.QRCodeBOx {
  width: 400rpx;
  height: 400rpx;
  display: block;
  margin: 40rpx auto;
}

.u-tap-btn {
  position: fixed;
  right: 20rpx;
  bottom: 150rpx;
}

.u-go-home {
  border-radius: 100%;
  width: 80rpx;
  height: 80rpx;
  border: 1px solid #eee;
  font-size: 20rpx;
  text-align: center;
  background-color: #fff;
  box-shadow: 0px 4rpx 8rpx rgba(0, 0, 0, 0.35);
  z-index: 2;
  opacity: 0.8;
  line-height: 80rpx;
  margin-bottom: 20rpx;
}

.u-go-home .iconfont {
  font-size: 40rpx;
}

.m-text-box {
  font-size: 24rpx;
  box-sizing: border-box;
  padding: 20rpx;
  color: #888;
  line-height: 40rpx;
}

.m-text-box label {
  padding-right: 10rpx;
}

.m-text-box1 {
  box-sizing: border-box;
  padding: 20rpx 36rpx;
  color: #888;
  line-height: 40rpx;
}

.m-text-box1 label {
  padding-right: 10rpx;
  font-size: 24rpx
}

.m-msk {
  position: fixed;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.5);
  top: 0;
  left: 0;
  z-index: 10;
}

.m-msk image {
  position: fixed;
  right: 30rpx;
  top: 0;
  width: 300rpx;
}
</style>
